package com.jdew.thkj.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.UserBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.SearchClickListener;
import com.jdew.thkj.utils.DeviceUtils;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.view.PopupWindowView;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.Calendar;
import java.util.HashMap;

import butterknife.Bind;
import cn.jpush.android.api.JPushInterface;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/9/7.
 */

public class LoginActivity extends BaseActivity {
    @Bind(R.id.login)
    Button login;
    @Bind(R.id.zhuce)
    TextView zhuce;
    @Bind(R.id.forget)
    TextView forget;
    @Bind(R.id.zh)
    EditText zh;
    @Bind(R.id.mima)
    EditText mima;
    @Bind(R.id.back)
    ImageView back;
    SharedPreferences sp;
    SharedPreferences.Editor editor;
    @Bind(R.id.cansee)
    ImageView cansee;
    @Bind(R.id.wx_login)
    RelativeLayout wxLogin;
    @Bind(R.id.num)
    TextView num;
    @Bind(R.id.quhao)
    LinearLayout quhao;
    @Bind(R.id.wx)
    TextView wx;
    @Bind(R.id.view)
    LinearLayout view;
    private int type = 0;
    private String telphone;
    private PopupWindowView popupWindowView;
    private IWXAPI mApi;

    @Override
    public int bindLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView(View view) {
        zhuce.setOnClickListener(this);
        forget.setOnClickListener(this);
        login.setOnClickListener(this);
        back.setOnClickListener(this);
        cansee.setOnClickListener(this);
        wxLogin.setOnClickListener(this);
        quhao.setOnClickListener(this);
        sp = getSharedPreferences("user", Activity.MODE_PRIVATE);
        editor = sp.edit();
        popupWindowView = new PopupWindowView(this);
        popupWindowView.setOnItemClickListener(new SearchClickListener() {
            @Override
            public void onItemClick(String position) {
                num.setText("+" + position);
                popupWindowView.dismiss();
            }
        });
        zh.setText(sp.getString("userPhone", ""));
        zh.setSelection(zh.getText().length());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                startActivity(MainActivity.class);
            }
            break;
            case R.id.zhuce: {
                startActivity(RegisterActivity.class);
            }
            break;

            case R.id.forget: {
                startActivity(FindPwActivity.class);
            }
            break;
            case R.id.quhao: {
                popupWindowView.showAsDropDown(quhao);
            }
            break;
            case R.id.cansee: {
                if (type == 0) {
                    cansee.setImageResource(R.mipmap.r_in);
                    mima.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    type = 1;
                } else {
                    cansee.setImageResource(R.mipmap.r_un);
                    mima.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    type = 0;
                }
                mima.setSelection(mima.getText().toString().length());
            }
            break;
            case R.id.login: {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                if (TextUtils.isEmpty(zh.getText()) || TextUtils.isEmpty(mima.getText())) {
                    ToastUtils.getInstance(this).showMessage("用户名和密码不能为空");
                    return;
                } else if (num.getText().toString().equals("+86")) {
                    if (!RegexValidateUtils.checkCellphone(zh.getText().toString())) {
                        ToastUtils.getInstance(this).showMessage("请输入正确的手机号码");
                    } else {
                        telphone = zh.getText().toString().trim();
                    }
                } else if (!num.getText().toString().equals("+86")) {
                    telphone = num.getText().toString().replace("+", "") + zh.getText().toString().trim();
                } else if (mima.getText().length() < 6 || mima.getText().length() > 16) {
                    ToastUtils.getInstance(this).showMessage("密码长度需要在6-16位之间");
                    return;
                }
                login();
            }
            break;
            case R.id.wx_login: {
                if (!RegexValidateUtils.isFastClick()) {
                    return;
                }
                mApi = WXAPIFactory.createWXAPI(this, AppConfig.APPID, true);
                mApi.registerApp(AppConfig.APPID);
                if (mApi != null && mApi.isWXAppInstalled()) {
                    SendAuth.Req req = new SendAuth.Req();
                    req.scope = "snsapi_userinfo";
                    req.state = "diandi_wx_login";
                    mApi.sendReq(req);
                } else {
                    ToastUtils.getInstance(this).showMessage("用户未安装微信");
                }
                break;
            }
            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(MainActivity.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mApi){
            mApi.detach();
        }
    }
    public void login() {
        if (!DeviceUtils.isNetworkAvalible(this)) {
            if (!this.isFinishing()) {
                ToastUtils.getInstance(this).showMessage("网络连接错误请检查!");
            }
            return;
        }
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        HashMap map = new HashMap();
        map.put("UserPhone", telphone);
        map.put("UserPwd", mima.getText().toString().trim());
        map.put("AndroidOrIos", "0");
        RetrofitManager.getInstance(AppConfig.BASE_URL).createReq(RequestApi.class).UserLogin(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + telphone + "UserPwd" + mima.getText().toString().trim() + "AndroidOrIos" + "0")).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<UserBean>() {
            @Override
            public void onCompleted() {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(LoginActivity.this).showMessage("登录异常");
                WeiboDialogUtils.closeDialog(mWeiboDialog);
            }

            @Override
            public void onNext(UserBean bean) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                if (bean.getCode().equals("0")) {
                    editor.putString("userName", bean.getData().getUserName());
                    editor.putString("userPhone", bean.getData().getUserPhone());
                    editor.putString("Alias", bean.getData().getUserPhone());
                    editor.putString("psw", bean.getData().getUserPwd());
                    editor.putString("UserWxId", bean.getData().getUserWxId());
                    editor.putString("mpid", bean.getData().getUserPid());
                    editor.putString("userId", bean.getData().getId());
                    editor.putString("UserImgUrl", bean.getData().getUserImgUrl());
                    editor.putString("UserSjPhone", bean.getData().getUserSjPhone());
                    editor.putString("Adzoneid", bean.getData().getUserPid().split("_")[3]);
                    editor.putString("Siteid", bean.getData().getUserPid().split("_")[2]);
                    editor.putString("SpareOne", bean.getData().getSpareOne());  //邀请码
                    editor.putString("SpareTwo", bean.getData().getSpareTwo());  //0是高级吗 1是低级码
                    editor.putString("nickName", bean.getData().getSpareThree());
                    editor.putString("AliAccount", bean.getData().getUserAlipay());
                    int sequence = getSequence();
                    editor.putInt("sequence", sequence);
                    editor.apply();
                    JPushInterface.setAlias(LoginActivity.this, sequence, bean.getData().getUserPhone());
                    ToastUtils.getInstance(LoginActivity.this).showMessage(bean.getMessage());
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                } else if (bean.getCode().equals("2") || bean.getCode().equals("1")) {
                    ToastUtils.getInstance(LoginActivity.this).showMessage(bean.getMessage());
                } else if (bean.getCode().equals("-1")) {
                    ToastUtils.getInstance(LoginActivity.this).showMessage(bean.getMessage());
                }
            }
        });
    }

    public static final int getSequence() {
        int result = getYear();
        result = 31 * result + getMonth();
        result = 31 * result + getDay();
        return result;
    }

    /**
     * 获取当前年份
     *
     * @return
     */
    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前月份
     *
     * @return
     */
    public static int getDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }
}
